package com.demo.Aspect;

import com.demo.service.RedisService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

@Service
@Aspect
public class BeforeServer {
    @Resource
    RedisService redisService;

    @Pointcut("execution(public * com.demo.controller.*.*(..))")
    public void allRequests(){}

    /**
     * 每次点击重置登录时间
     * @param proceedingJoinPoint 切点
     * @return 对应方法的参数
     * @throws Throwable 各种异常
     */
    @Around(value = "allRequests()")
    public Object lengthenSessionTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object[] args = proceedingJoinPoint.getArgs();
        HttpSession session=null;
        HttpServletRequest request=null;
        HttpServletResponse response=null;
        for(Object obj:args){
            if(obj instanceof HttpSession){
                session= (HttpSession) obj;
            }
            if(obj instanceof HttpServletRequest){
                request= (HttpServletRequest) obj;
            }
            if(obj instanceof HttpServletResponse){
                response= (HttpServletResponse) obj;
            }
        }
        String sessionId;
        if(request!=null){
            sessionId=request.getHeader("sessionId");
            redisService.resetKeyTime(sessionId);
        }
        return proceedingJoinPoint.proceed();
    }
}
